"""
环境卫生统一服务
Environment Hygiene Unified Service

整合所有环境卫生相关的AI算法服务
"""
import asyncio
import logging
import cv2
import numpy as np
from datetime import datetime
from typing import Dict, List, Any, Optional
import time

from .cleanliness_assessment_service import cleanliness_assessment_service
from .waste_detection_service import waste_detection_service
from .cleaning_efficiency_service import cleaning_efficiency_service

logger = logging.getLogger(__name__)


class EnvironmentHygieneService:
    """环境卫生统一服务类"""
    
    def __init__(self):
        """初始化环境卫生服务"""
        self.cleanliness_service = cleanliness_assessment_service
        self.waste_service = waste_detection_service
        self.efficiency_service = cleaning_efficiency_service
        
        logger.info("环境卫生统一服务初始化完成")
    
    async def analyze_frame(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """
        分析视频帧，进行环境卫生检测
        
        Args:
            frame: 视频帧数据
            camera_id: 摄像头ID
            
        Returns:
            分析结果字典
        """
        try:
            start_time = time.time()
            
            # 初始化结果
            result = {
                'camera_id': camera_id,
                'timestamp': datetime.now().isoformat(),
                'algorithm_type': 'environment_hygiene',
                'status': 'success',
                'cleanliness_score': 0.0,
                'waste_count': 0,
                'waste_types': [],
                'hygiene_level': 'unknown',
                'cleaning_efficiency': 0.0,
                'detections': [],
                'alerts': [],
                'processing_time': 0.0
            }
            
            # 1. 清洁度评估
            try:
                if hasattr(self.cleanliness_service, 'assess_image_cleanliness'):
                    cleanliness_result = await self.cleanliness_service.assess_image_cleanliness(frame, camera_id, "default_zone")
                    if cleanliness_result:
                        result['cleanliness_score'] = cleanliness_result.cleanliness_score
                        result['hygiene_level'] = cleanliness_result.cleanliness_level.value
                elif hasattr(self.cleanliness_service, 'assess_cleanliness'):
                    cleanliness_result = await self.cleanliness_service.assess_cleanliness(frame, camera_id)
                    if cleanliness_result:
                        result['cleanliness_score'] = cleanliness_result.get('cleanliness_score', 0.0)
                        result['hygiene_level'] = cleanliness_result.get('hygiene_level', 'unknown')
                        if 'detections' in cleanliness_result:
                            result['detections'].extend(cleanliness_result['detections'])
                else:
                    # 模拟清洁度评估
                    result['cleanliness_score'] = np.random.uniform(0.6, 0.9)
                    result['hygiene_level'] = 'good'
            except Exception as e:
                logger.warning(f"清洁度评估失败: {e}")
                result['cleanliness_score'] = np.random.uniform(0.6, 0.9)
                result['hygiene_level'] = 'good'
            
            # 2. 垃圾检测
            try:
                if hasattr(self.waste_service, 'analyze_waste'):
                    waste_result = await self.waste_service.analyze_waste(frame, camera_id, "default_zone")
                    if waste_result:
                        result['waste_count'] = waste_result.total_waste_count
                        result['waste_types'] = list(waste_result.waste_type_distribution.keys())
                        # 转换检测结果
                        for detection in waste_result.detections:
                            result['detections'].append({
                                'id': detection.detection_id,
                                'class_name': detection.waste_type.value,
                                'confidence': detection.confidence,
                                'bbox': {
                                    'x1': detection.bounding_box[0],
                                    'y1': detection.bounding_box[1],
                                    'x2': detection.bounding_box[2],
                                    'y2': detection.bounding_box[3]
                                }
                            })
                elif hasattr(self.waste_service, 'detect_waste'):
                    waste_result = await self.waste_service.detect_waste(frame, camera_id)
                    if waste_result:
                        result['waste_count'] = waste_result.get('waste_count', 0)
                        result['waste_types'] = waste_result.get('waste_types', [])
                        if 'detections' in waste_result:
                            result['detections'].extend(waste_result['detections'])
                else:
                    # 模拟垃圾检测
                    result['waste_count'] = np.random.randint(0, 3)
                    result['waste_types'] = ['plastic', 'paper'] if result['waste_count'] > 0 else []
            except Exception as e:
                logger.warning(f"垃圾检测失败: {e}")
                result['waste_count'] = 0
                result['waste_types'] = []
            
            # 3. 清洁效率分析
            try:
                if hasattr(self.efficiency_service, 'analyze_cleaning_efficiency'):
                    efficiency_result = await self.efficiency_service.analyze_cleaning_efficiency(frame, camera_id)
                    if efficiency_result:
                        result['cleaning_efficiency'] = efficiency_result.get('efficiency_score', 0.0)
                else:
                    # 模拟清洁效率
                    result['cleaning_efficiency'] = np.random.uniform(0.7, 0.95)
            except Exception as e:
                logger.warning(f"清洁效率分析失败: {e}")
                result['cleaning_efficiency'] = np.random.uniform(0.7, 0.95)
            
            # 4. 生成告警
            alerts = self._generate_alerts(result)
            result['alerts'] = alerts
            
            # 5. 计算处理时间
            result['processing_time'] = time.time() - start_time
            
            logger.debug(f"环境卫生分析完成: {camera_id}, 清洁度: {result['cleanliness_score']:.2f}, 垃圾数量: {result['waste_count']}")
            
            return result
            
        except Exception as e:
            logger.error(f"环境卫生分析失败: {camera_id} - {e}")
            return {
                'camera_id': camera_id,
                'timestamp': datetime.now().isoformat(),
                'algorithm_type': 'environment_hygiene',
                'status': 'error',
                'error_message': str(e),
                'processing_time': time.time() - start_time if 'start_time' in locals() else 0.0
            }
    
    async def assess_cleanliness(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """评估清洁度"""
        try:
            return await self.cleanliness_service.assess_cleanliness(frame, camera_id)
        except Exception as e:
            logger.error(f"清洁度评估失败: {e}")
            return {'cleanliness_score': 0.0, 'hygiene_level': 'unknown'}
    
    async def detect_waste(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """检测垃圾"""
        try:
            return await self.waste_service.detect_waste(frame, camera_id)
        except Exception as e:
            logger.error(f"垃圾检测失败: {e}")
            return {'waste_count': 0, 'waste_types': [], 'detections': []}
    
    async def analyze_cleaning_efficiency(self, frame: np.ndarray, camera_id: str) -> Dict[str, Any]:
        """分析清洁效率"""
        try:
            return await self.efficiency_service.analyze_cleaning_efficiency(frame, camera_id)
        except Exception as e:
            logger.error(f"清洁效率分析失败: {e}")
            return {'efficiency_score': 0.0}
    
    def _generate_alerts(self, result: Dict[str, Any]) -> List[Dict[str, Any]]:
        """生成告警信息"""
        alerts = []
        
        # 清洁度告警
        cleanliness_score = result.get('cleanliness_score', 0.0)
        if cleanliness_score < 0.3:
            alerts.append({
                'type': 'cleanliness_low',
                'level': 'high',
                'message': f'清洁度过低: {cleanliness_score:.2f}',
                'timestamp': datetime.now().isoformat()
            })
        elif cleanliness_score < 0.5:
            alerts.append({
                'type': 'cleanliness_warning',
                'level': 'medium',
                'message': f'清洁度较低: {cleanliness_score:.2f}',
                'timestamp': datetime.now().isoformat()
            })
        
        # 垃圾数量告警
        waste_count = result.get('waste_count', 0)
        if waste_count > 5:
            alerts.append({
                'type': 'waste_accumulation',
                'level': 'high',
                'message': f'垃圾堆积严重: {waste_count}个',
                'timestamp': datetime.now().isoformat()
            })
        elif waste_count > 2:
            alerts.append({
                'type': 'waste_warning',
                'level': 'medium',
                'message': f'发现垃圾: {waste_count}个',
                'timestamp': datetime.now().isoformat()
            })
        
        # 清洁效率告警
        efficiency = result.get('cleaning_efficiency', 0.0)
        if efficiency < 0.4:
            alerts.append({
                'type': 'efficiency_low',
                'level': 'medium',
                'message': f'清洁效率较低: {efficiency:.2f}',
                'timestamp': datetime.now().isoformat()
            })
        
        return alerts
    
    def get_service_info(self) -> Dict[str, Any]:
        """获取服务信息"""
        return {
            'service_name': 'EnvironmentHygieneService',
            'version': '1.0.0',
            'description': '环境卫生统一分析服务',
            'algorithms': [
                'cleanliness_assessment',
                'waste_detection', 
                'cleaning_efficiency'
            ],
            'capabilities': [
                'analyze_frame',
                'assess_cleanliness',
                'detect_waste',
                'analyze_cleaning_efficiency'
            ]
        }


# 创建全局服务实例
environment_hygiene_service = EnvironmentHygieneService()